package com.qingchi.web.service;

import com.socialuni.center.sdk.service.login.CenterLoginService;
import com.socialuni.social.model.RO.user.SocialUserDetailRO;
import com.socialuni.social.model.RO.user.UserDetailVO;
import com.socialuni.uniapp.model.ProviderLoginQO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author qinkaiyuan
 * @date 2020-04-12 2:27
 */
@Service
public class LoginService {

    @Resource
    CenterLoginService centerLoginService;

    public UserDetailVO providerLogin(ProviderLoginQO loginQO) {
        SocialUserDetailRO userDO = centerLoginService.providerLogin(loginQO);

        // 这里去做app独有的逻辑；
        return null;
    }

    /*public AppInitDataVO getUserInitData(SocialUserDO user, boolean isLogin) {
        AppInitDataVO appInitData = new AppInitDataVO();
        Integer devId = DevAccountUtils.getDevId();
        //是否为登陆接口，登陆接口返回token信息
        if (isLogin) {
            Long devNum = DevAccountUtils.getDevNum();
            //生成userToken
            String userToken = TokenUtils.generateTokenById(user.getId(), devNum);
            TokenDO tokenDO = tokenRepository.save(new TokenDO(userToken, user.getId()));
            appInitData.setTokenCode(tokenDO.getTokenCode());
        }
        //user
        appInitData.setUser(new UserDetailBO(user, true).toVO());
        //notifies
        List<NotifyDO> notifyDOS = notifyRepository.findTop20ByReceiveUserIdAndTypeInOrderByHasReadDescIdDesc(user.getId(), NotifyType.comments);
        appInitData.setNotifies(UnreadNotifyVO.unreadNotifyDOToVOS(notifyDOS, user));
        //userDistricts
        *//*List<DistrictVO> userDistrictVOS = DistrictVO.districtDOToVOS(districtDOS.stream()
                .map(userDistrictDO -> {
                    return DistrictUtils.get(userDistrictDO.getDistrictId());
                })
                .collect(Collectors.toList()));
        appInitData.setUserDistricts(userDistrictVOS);*//*
        //chats
        List<ChatVO> chatVOs = chatUserService.getChats(user);
        appInitData.setChats(chatVOs);
        //微信订阅模板
        appInitData.setTalkTemplateIds(WxConst.talkTemplateIds);
        appInitData.setMessageTemplateIds(WxConst.messageTemplateIds);
        appInitData.setCommentTemplateIds(WxConst.commentTemplateIds);
        appInitData.setReportTemplateIds(WxConst.reportTemplateIds);

        //微信新版订阅模板
        appInitData.setWx_talkTemplateId(WxConst.talk_template_id);
        appInitData.setWx_commentTemplateId(WxConst.comment_template_id);
        appInitData.setWx_reportResultTemplateId(WxConst.report_result_template_id);
        appInitData.setWx_violationTemplateId(WxConst.violation_template_id);

        //qq订阅模板
        appInitData.setQq_talkTemplateId(QQConst.talk_template_id);
        appInitData.setQq_commentTemplateId(QQConst.comment_template_id);
        appInitData.setQq_reportResultTemplateId(QQConst.report_result_template_id);
        appInitData.setQq_violationTemplateId(QQConst.violation_template_id);
        return appInitData;
    }*/

    /*public ResultRO<?> phoneLogin(PhoneLoginQO loginVO) {
        //所有平台，手机号登陆方式代码一致
        //登录的时候如果没有手机号，则手机号注册成功，自动注册一个user，用户名待填，自动生成一个昵称，密码待填，头像待上传
        //如果已经登录过，则返回那个已经注册的user，根据手机号获取user，返回登录成功
        //记录用户错误日志
        String phoneNum = loginVO.getPhoneNum();
        String authCode = loginVO.getAuthCode();
        //如果存在非数字
        //1.为空 2. 包含非数字 3.不为11位 ，返回
        if (StringUtils.isEmpty(phoneNum) || IntegerUtils.strHasNoNumber(phoneNum) || phoneNum.length() != 11) {
            logger.error("有人跳过前端，直接访问后台，错误手机号");
            return new ResultRO<>("请输入正确的手机号");
        }
        //校验验证码，传null用户记录日志
        ResultRO<String> resultRO = authCodeService.verifyAuthCode(phoneNum, authCode, null);
        if (resultRO.hasError()) {
            return resultRO;
        }
        //如果手机号已经存在账户，则直接使用，正序获取第一个用户
        Optional<SocialUserDO> userDOOptional = userRepository.findFirstByPhoneNumOrderByIdAsc(phoneNum);
        SocialUserDO dbUser;
        //有用户返回，没有创建
        String platform = loginVO.getPlatform();
        if (userDOOptional.isPresent()) {
            dbUser = userDOOptional.get();
        } else {
            dbUser = userService.createUser(phoneNum, platform);
            AccountDO accountDO = new AccountDO(platform, loginVO.getProvider(), dbUser.getId());
            accountRepository.save(accountDO);
        }
        //则更新用户手机号
        return new ResultRO<>(loginService.getUserInitData(dbUser, true));
    }*/

    /*private Optional<AccountDO> getAccountDO(String provider, UnionIdResult unionIdResult) {
        Optional<AccountDO> optionalAccount = Optional.empty();
        String openId = unionIdResult.getOpenid();
        String unionId = unionIdResult.getUnionid();
        //qq平台
        if (ProviderType.qq.equals(provider)) {
            if (org.apache.commons.lang.StringUtils.isNotEmpty(unionId)) {
                optionalAccount = accountRepository.findFirstOneByQqUnionIdOrderByIdAsc(unionId);
            }
            if (!optionalAccount.isPresent()) {
                optionalAccount = accountRepository.findFirstOneByQqMpOpenIdOrderByIdAsc(openId);
            }
            //wx平台
        } else if (ProviderType.wx.equals(provider)) {
            //unionId查询
            if (org.apache.commons.lang.StringUtils.isNotEmpty(unionId)) {
                optionalAccount = accountRepository.findFirstOneByWxUnionIdOrderByIdAsc(unionId);
            }
            //没有的话openId查询
            if (!optionalAccount.isPresent()) {
                optionalAccount = accountRepository.findFirstOneByWxMpOpenIdOrderByIdAsc(openId);
            }
        }
        return optionalAccount;
    }*/

    /*public ResultRO<?> providerLogin(ProviderLoginQO loginVO) {
        //非手机号登录
        // 区分
        //如果是app
        UnionIdResult unionIdResult = ProviderUtil.getUnionId(loginVO.toUnionIdData());

        assert unionIdResult != null;

        String openId = unionIdResult.getOpenid();
        String unionId = unionIdResult.getUnionid();


        String platform = loginVO.getPlatform();
        String provider = loginVO.getProvider();

        AccountDO accountDO;
        SocialUserDO dbUser;
        Date curDate = new Date();

        Optional<AccountDO> optionalAccount = getAccountDO(loginVO.getProvider(), unionIdResult);
        //如果已经注册过
        if (optionalAccount.isPresent()) {
            accountDO = optionalAccount.get();
            dbUser = UserUtils.get(accountDO.getUserId());
            //如果账号被封禁则报错
            if (UserStatus.violation.equals(dbUser.getStatus())) {
                //账号被封禁，多少天后解封
                UserDetailDO userDetailDO = UserUtils.getUserDetail(dbUser.getId());
                return new ResultRO<>(ErrorMsgUtil.getErrorCode605ContactServiceValue(userDetailDO.getViolationEndTime()));
            }
            //否则就会走最下面
        } else {
            dbUser = userService.createUser(loginVO);
            accountDO = new AccountDO(platform, provider, dbUser.getId());
        }

        //更新account信息,登陆方式
        if (ProviderType.qq.equals(provider)) {
            if (PlatformType.mp.equals(platform)) {
                accountDO.setQqMpOpenId(openId);
            } else {
                accountDO.setQqAppOpenId(openId);
            }
            accountDO.setQqUnionId(unionId);
        } else if (ProviderType.wx.equals(provider)) {
            if (PlatformType.mp.equals(platform)) {
                accountDO.setWxMpOpenId(openId);
                //微信时支持绑手机号使用，存储下sessionkey
                accountDO.setSessionKey(unionIdResult.getSession_key());
            } else {
                accountDO.setWxAppOpenId(openId);
            }
            accountDO.setWxUnionId(unionId);
        }
        //最后一次登陆的渠道，还有登陆方式,每次登陆都更新渠道信息
        accountDO.setPlatform(platform);
        accountDO.setProvider(provider);
        accountDO.setClientid(loginVO.getClientid());
        accountDO.setUpdateTime(curDate);
        dbUser.setPlatform(platform);
        dbUser.setProvider(provider);
        userRepository.save(dbUser);
        //只有微信小程序才会赋值
        accountRepository.save(accountDO);

        return new ResultRO<>(loginService.getUserInitData(dbUser, true));
    }*/
}
